iT邦幫忙

2023 iThome 鐵人賽

DAY 18
0

Strapi 是一個 headless CMS , 可以將 Content 儲存在其中

Astro.js 可以將 Content 取出並顯示出來

下面我們來說明在 Astro.js 如何整合 Strapi 吧~

前置作業

  1. An Astro project - If you don’t have an Astro project yet, our Installation guide will get you up and running in no time.

  2. A Strapi CMS server - You can set up a Strapi server on a local environment.

Creating the API wrapper

Create a new file at lib/strapi.ts and add the following wrapper function to interact with the Strapi API:

// lib/strapi.ts
interface Props {
  endpoint: string;
  query?: Record<string, string>;
  wrappedByKey?: string;
  wrappedByList?: boolean;
}

/**
 * Fetches data from the Strapi API
 * @param endpoint - The endpoint to fetch from
 * @param query - The query parameters to add to the url
 * @param wrappedByKey - The key to unwrap the response from
 * @param wrappedByList - If the response is a list, unwrap it
 * @returns
 */
export default async function fetchApi<T>({
  endpoint,
  query,
  wrappedByKey,
  wrappedByList,
}: Props): Promise<T> {
  if (endpoint.startsWith('/')) {
    endpoint = endpoint.slice(1);
  }

  const url = new URL(`${import.meta.env.STRAPI_URL}/api/${endpoint}`);

  if (query) {
    Object.entries(query).forEach(([key, value]) => {
      url.searchParams.append(key, value);
    });
  }
  const res = await fetch(url.toString());
  let data = await res.json();

  if (wrappedByKey) {
    data = data[wrappedByKey];
  }

  if (wrappedByList) {
    data = data[0];
  }

  return data as T;
}

Displaying a list of articles

  1. Update your home page src/pages/index.astro to display a list of blog posts, each with a description and a link to its own page.
  2. Import the wrapper function and the interface. Add the following API call to fetch your articles and return a list:
// src/pages/index.astro
---
import fetchApi from '../lib/strapi';
import type Article from '../interfaces/article';

const articles = await fetchApi<Article[]>({
  endpoint: 'articles', // the content type to fetch
  wrappedByKey: 'data', // the key to unwrap the response
});
---

參考資料


上一篇
[Day 17] Astro - Fonts
下一篇
[Day 19] Astro - I18N
系列文
Micro-Frontend 的新夥伴:Astro.js 的應用與研究20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言